#include "linkereditwidget.h"
#include "ui_linkereditwidget.h"
#include "Narration/narrationnode.h"
#include <QMessageBox>
LinkerEditWidget::LinkerEditWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LinkerEditWidget)
{
    ui->setupUi(this);
    this->setWindowModality(Qt::ApplicationModal);
    this->resize(1000,1000);
    this->setMinimumSize(800,800);
    this->setWindowTitle("编辑映射器");
    this->setWindowIcon(QIcon(":/res/icon/conditionIcon.png"));
    QButtonGroup btnG;
    btnG.setExclusive(true);
    btnG.addButton(ui->branchBtn);
    btnG.addButton(ui->nodeBtn);
    connect(ui->conditionBtn,&QPushButton::clicked,this,[=](){
        AddConditionItem();
    });
    connect(ui->actionBtn,&QPushButton::clicked,this,[=](){
        AddActionItem();
    });
    connect(ui->deleteConditionBtn,&QPushButton::clicked,this,[=](){
        DeleteCurItem(ui->conditionList);
    });
    connect(ui->deleteActionBtn,&QPushButton::clicked,this,[=](){
        DeleteCurItem(ui->actionList);
    });
    connect(ui->saveBtn,&QPushButton::clicked,this,[=](){
        SaveBtn();
    });
}

LinkerEditWidget::~LinkerEditWidget()
{
    delete ui;
}

void LinkerEditWidget::SetName(QString name)
{
    ui->NameEdit->setText(name);
}

void LinkerEditWidget::AddConditionItem()
{
    LinkerItem* linkerItem = new LinkerItem(this);
    //添加到项中
    QListWidgetItem* item = new QListWidgetItem();
    item->setSizeHint(QSize(400,200));
    ui->conditionList->addItem(item);
    ui->conditionList->setItemWidget(item,linkerItem);
}

void LinkerEditWidget::AddConditionItem(Condition *c)
{
    LinkerItem* linkerItem = new LinkerItem(this);
    //添加到项中
    QListWidgetItem* item = new QListWidgetItem();
    item->setSizeHint(QSize(400,200));
    ui->conditionList->addItem(item);
    ui->conditionList->setItemWidget(item,linkerItem);
    linkerItem->WriteCondition(c);
}

void LinkerEditWidget::AddActionItem()
{
    LinkerItem* linkerItem = new LinkerItem(this,false);
    //添加到项中
    QListWidgetItem* item = new QListWidgetItem();
    item->setSizeHint(QSize(400,200));
    ui->actionList->addItem(item);
    ui->actionList->setItemWidget(item,linkerItem);
}

void LinkerEditWidget::AddActionItem(Action *a)
{
    LinkerItem* linkerItem = new LinkerItem(this,false);
    //添加到项中
    QListWidgetItem* item = new QListWidgetItem();
    item->setSizeHint(QSize(400,200));
    ui->actionList->addItem(item);
    ui->actionList->setItemWidget(item,linkerItem);
    linkerItem->WriteAction(a);
}

void LinkerEditWidget::ReadNodeLinker()
{
    //复原
    ui->noBtn->setChecked(true);
    ui->nodeIdEdit->setText("");
    ui->optionBtn->setChecked(false);
    ui->optionEdit->setText("");
    ClearList();

    Linker* linker = GameManager::Instance().curNode->linkers.at(curRow);
    //name
    ui->NameEdit->setText(linker->name);
    //Radio buttons
    if(!linker->branchOptionText.isEmpty())
    {
        ui->optionBtn->setChecked(true);
        ui->optionEdit->setText(linker->branchOptionText);
    }
    if(linker->branchId >= 0)
    {
        ui->branchBtn->setChecked(true);
    }
    if(linker->cycleId >=0 && linker-> branchId < 0)
    {
        ui->nodeBtn->setChecked(true);
        ui->nodeIdEdit->setText(QString::number(linker->cycleId));
    }
    //Conditions
    for (int i = 0;i < linker->conditions.count();i++)
    {
        AddConditionItem(linker->conditions.at(i));
    }
    //Actions
    for (int i = 0;i < linker->actions.count();i++)
    {
        AddActionItem(linker->actions.at(i));
    }
}

void LinkerEditWidget::closeEvent(QCloseEvent *event)
{
    QWidget::closeEvent(event);
    QMessageBox m;
    QPushButton okBtn("确定");
    QPushButton cancelBtn("取消");
    m.setWindowTitle("提示");
    m.setWindowIcon(QIcon(":/res/icon/tip.png"));
    m.setText("内容未保存，确定退出编辑吗？\n关闭后所作修改将不会生效。");
    m.addButton(&okBtn,QMessageBox::AcceptRole);
    m.addButton(&cancelBtn,QMessageBox::RejectRole);
    m.show();
    //对话框阻塞，等待用户选择
    m.exec();
    if(m.clickedButton() == &cancelBtn)
    {
        event->ignore();
    }
    emit EventCenter::Instance().LinkerEditFinish();
}

void LinkerEditWidget::SaveBtn()
{
    Linker* linker = GameManager::Instance().curNode->linkers.at(curRow);
    linker->name = ui->NameEdit->text().isEmpty()?"映射器":ui->NameEdit->text();
    if(ui->optionBtn->isChecked())
    {
        QString option = ui->optionEdit->text().isEmpty()?"选项":ui->optionEdit->text();
        linker->branchOptionText = option;
    }
    //记录不合法的condition和action
    int wrong = 0;
    //conditions
    linker->conditions.clear();
    for(int i = 0;i < ui->conditionList->count();i++)
    {
        QWidget* w = ui->conditionList->itemWidget(ui->conditionList->item(i));
        LinkerItem* li = dynamic_cast<LinkerItem*>(w);
        if(li)
        {
            Condition* c = li->ReadCondition();
            if(!c)
            {
                wrong++;
                continue;
            }
            linker->conditions.push_back(c);
        }
    }
    //actions
    linker->actions.clear();
    for(int i = 0;i < ui->actionList->count();i++)
    {
        QWidget* w = ui->actionList->itemWidget(ui->actionList->item(i));
        LinkerItem* li = dynamic_cast<LinkerItem*>(w);
        if(li)
        {
            Action* a = li->ReadAction();
            if(!a)
            {
                wrong++;
                continue;
            }
            linker->actions.push_back(a);
        }
    }
    //跳转动作
    //跳转到某节点
    if(ui->nodeBtn->isChecked())
    {
        linker->cycleId = ui->nodeIdEdit->text().toInt();
    }
    //跳转到某分支
    if(ui->branchBtn->isChecked())
    {
        //防止重复创建多余节点
        if(linker->branchId >= 0)
            return;
        linker->cycleId = -1;
        NarrationNode* node = new NarrationNode();
        linker->branchId = node->id;
        node->parentId = GameManager::Instance().curNode->id;
    }
    if(ui->noBtn->isChecked())
    {
        linker->branchId = -1;
        linker->cycleId = -1;
        //TODO 删除整个分支
    }
    GameManager::Instance().curNode->linkers[curRow] = linker;
    //弹出对话框，提示不合格
    if(wrong > 0)
    {
        QString warning = "编辑的条件(Condition)动作(Action)集里有" +
                QString::number(wrong) + "个不合法，这些条件和动作将不会被保留！";
        QMessageBox m;
        m.information(nullptr,"提示",warning);
        m.setModal(true);
        m.show();
    }
    emit EventCenter::Instance().RefreshCurNodeItem();
    //调用close会触发closeEvent()。需要保证仅点击右上角x时触发close事件
    this->hide();
    emit EventCenter::Instance().LinkerEditFinish();
}

void LinkerEditWidget::ClearList()
{
    for (int i = 0;i < ui->conditionList->count();i++)
    {
        QListWidgetItem* item = ui->conditionList->item(i);
        QWidget *w = ui->conditionList->itemWidget(item);
        ui->conditionList->removeItemWidget(item);
        if(w)
            delete w;
    }
    ui->conditionList->clear();

    for (int i = 0;i < ui->actionList->count();i++)
    {
        QListWidgetItem* item = ui->actionList->item(i);
        QWidget *w = ui->actionList->itemWidget(item);
        ui->actionList->removeItemWidget(item);
        if(w)
            delete w;
    }
    ui->actionList->clear();
}

void LinkerEditWidget::DeleteCurItem(QListWidget *w)
{
    if(w->currentRow() < 0)
        return;
    QListWidgetItem* i = w->currentItem();
    QWidget* iw = w->itemWidget(i);
    w->removeItemWidget(i);
    w->takeItem(w->currentRow());
    delete iw;
    delete i;
}
